package mobi.zeedev.flyingsaucer.scala.delegates

import android.content.SharedPreferences
import mobi.zeedev.flyingsaucer.common.CredentialsModule.impl.Credentials
import mobi.zeedev.flyingsaucer.common.CredentialsModule.interfaces.{ICredentials, IPreferenceCredentials}
import java.util.Date
import com.google.inject.Inject

//import scala.collection.JavaConversions._

/**
 * User: James
 * Date: 2/7/11
 * Time: 5:04 AM
 */

@com.google.inject.Singleton
class AutoPreferenceCredentials @Inject() (val prefs : SharedPreferences) extends PropertyCredentialsImpl with IPreferenceCredentials {

  //  @Inject
  //  protected var prefs: SharedPreferences = _


  //@Named("lastMemberId") memeberId: java.lang.Integer

  @Inject
  def bindFromPreferences(): Unit = {


    setStoreNumber(prefs.getString(Credentials.STORE_NUMBER, ""))


    setCardNumber(prefs.getString(Credentials.CARD_NUMBER, ""))


    setPassword(prefs.getString(Credentials.PASSWORD, ""))


    setUfoAutoLogin(prefs.getBoolean(Credentials.UFO_AUTO_LOGIN, false))


    setUfoRemember(prefs.getBoolean(Credentials.UFO_REMEMBER, false))


    setUfoMouMember(prefs.getBoolean(Credentials.UFO_MOU_MEMBER, false))


    var time: Long = prefs.getLong(Credentials.UFO_ORIGIN_DATE, 0l)


    if (time == 0) {
      originDate := null
    } else {
      var d: Date = new Date
      d.setTime(time)
      originDate := d
    }


    //    credentials.setUserName (prefs.getString (Credentials.USER_NAME, "") )
    //    var testInt: Integer = prefs.getInt (Credentials.MEMBER_ID, 0)
    //    credentials.setMemberId (testInt)


  }

  //memberIdIn: java.lang.Integer
  def bindToPreferences(): Unit = {

    val editor = prefs.edit




    editor.putString(Credentials.STORE_NUMBER, storeNumber.value)


    editor.putString(Credentials.CARD_NUMBER, cardNumber.value)


    editor.putString(Credentials.PASSWORD, password.value)


    editor.putString(Credentials.USER_NAME, userName.value)


    editor.putString(Credentials.PASSWORD_HASH, passwordHash.value)


    editor.putBoolean(Credentials.UFO_AUTO_LOGIN, ufoAutoLogin.value.booleanValue)


    editor.putBoolean(Credentials.UFO_REMEMBER, ufoRemember.value.booleanValue)


    editor.putInt(Credentials.MEMBER_ID, memberId.value.asInstanceOf[scala.Int])


    editor.putLong(Credentials.UFO_ORIGIN_DATE, if (originDate.value != null) originDate.value.getTime else 0l)


    editor.putBoolean(Credentials.UFO_MOU_MEMBER, ufoMouMember.value.booleanValue)

    editor.commit


  }

  /*  def bindToPreferencesWithDefaultMemberId: Unit = {
    bindToPreferences(memberId.value)

  }*/

  def bindConditionallyToPreferences: Unit = {
    if (ufoRemember.value.booleanValue) {
      bindToPreferences
    }

  }

  def getCredentials: ICredentials = {
    this
  }


}